C++ math

🗖 The math library in C++ offers a large number of functions for carrying out mathematical calculations. These functions, which are included in the header (short for "C Math"), include trigonometric functions, power, square root, logarithms, rounding, and more.

Commonly Used Math Functions in <cmath>

Function

Description

Example

abs(x)

Returns the absolute value of x.

abs(-5) → 5

sqrt(x)

Returns the square root of x.

sqrt(16) → 4

pow(base, exp)

Returns base raised to the power exp.

pow(2, 3) → 8

sin(x)

Returns the sine of x (in radians).

sin(3.14 / 2) → 1.0

cos(x)

Returns the cosine of x (in radians).

cos(0) → 1.0

tan(x)

Returns the tangent of x (in radians).

tan(0) → 0

log(x)

Returns the natural logarithm of x.

log(1) → 0

log10(x)

Returns the base-10 logarithm of x.

log10(100) → 2

exp(x)

Returns e^x (exponential function).

exp(1) → 2.71828...

ceil(x)

Returns the smallest integer ≥ x.

ceil(3.2) → 4

floor(x)

Returns the largest integer ≤ x.

floor(3.7) → 3

round(x)

Rounds x to the nearest integer.

round(2.5) → 3

fmod(x, y)

Returns the remainder of x / y.

fmod(7, 3) → 1

hypot(x, y)

Returns sqrt(x^2 + y^2).

hypot(3, 4) → 5



Example 01:

#include <iostream>
#include <cmath> // Include the cmath header

using namespace std;

int main() {
    double num1 = -5.6, num2 = 16, base = 2, exp = 3;

    // Absolute value
    cout << "Absolute value of " << num1 << ": " << abs(num1) << endl;

    // Square root
    cout << "Square root of " << num2 << ": " << sqrt(num2) << endl;

    // Power
    cout << base << " raised to the power " << exp << ": " << pow(base, exp) << endl;

    // Trigonometric functions
    double angle = 3.14159 / 4; // 45 degrees in radians
    cout << "sin(45 degrees): " << sin(angle) << endl;
    cout << "cos(45 degrees): " << cos(angle) << endl;

    // Logarithm
    cout << "Natural logarithm of 2: " << log(2) << endl;
    cout << "Base-10 logarithm of 100: " << log10(100) << endl;

    // Rounding functions
    cout << "Ceiling of " << num1 << ": " << ceil(num1) << endl;
    cout << "Floor of " << num1 << ": " << floor(num1) << endl;
    cout << "Round of " << num1 << ": " << round(num1) << endl;

    // Hypotenuse
    cout << "Hypotenuse of a right triangle with sides 3 and 4: " << hypot(3, 4) << endl;

    return 0;
}

← Back Next →

Comments

Popular posts from this blog

Wrapper Class

Information Security & Essential Terminology

Information Security Threat Categories